<template>
    <div class="address-edit-box">
        <van-nav-bar :title="`${type === 'add' ? '新增地址' : '编辑地址'}`" fixed left-text="返回" left-arrow
                     @click-left="goBack">
            <template #right>
                <van-icon name="fire-o" color="#ee0a24" size="20"/>
            </template>
        </van-nav-bar>
        <van-address-edit
                class="edit"
                :area-list="areaList"
                :address-info="addressInfo"
                :show-delete="type === 'edit'"
                show-set-default
                show-search-result
                :search-result="searchResult"
                :area-columns-placeholder="['请选择', '请选择', '请选择']"
                @save="onSave"
                @delete="onDelete"
        />

    </div>
</template>

<script>
    import {Toast} from 'vant'
    import sHeader from '../../../components/SimpleHeader'
    import {addAddress, EditAddress, DeleteAddress, getAddressDetail} from '../../../api/address'
    import {tdist} from '../../../common/js/utils'
    import {areaList as globalAreaList} from '@vant/area-data';
    import store from "../../../store";

    export default {
        name: "addressDetail",
        components: {
            sHeader
        },
        data() {
            return {
                areaList: {
                    province_list: {},
                    city_list: {},
                    county_list: {}
                },
                searchResult: [],
                type: this.$route.query.type,
                addressId: '',
                addressInfo: {},
                from: '',
                addressItem: {},
                globalCode: '',
            }
        },
        async mounted() {
            const {addressId, type, from} = this.$route.query
            this.from = from;
            this.type = type;
            this.addressId = addressId;
            // 省市区列表构造
            this.areaList.province_list = globalAreaList.province_list
            this.areaList.city_list = globalAreaList.city_list
            this.areaList.county_list = globalAreaList.county_list

            if (type === 'edit') {
                this.getDetail(addressId)
            }
        },
        methods: {
            //配置地址信息
            getDetail(addressId) {
                getAddressDetail(addressId).then(res => {
                    const detail = res.data

                    this.setCode(detail);
                    //设置地址信息
                    this.addressInfo = {
                        id: detail.id,
                        name: detail.name,
                        tel: detail.phoneNumber,
                        province: detail.province,
                        city: detail.city,
                        county: detail.region,
                        addressDetail: detail.detailAddress,
                        areaCode: this.setCode(detail),
                        isDefault: detail.defaultStatus === 1 ? true : false
                    }
                })
            },
            //设置postcode
            setCode(detail) {
                let _areaCode = ''
                const province = tdist.getLev1()
                Object.entries(this.areaList.county_list).forEach(([id, text]) => {
                    // 先找出当前对应的区
                    if (text === detail.region) {
                        // 找到区对应的几个省份
                        const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
                        // 找到区对应的几个市区
                        const cityItem = Object.entries(this.areaList.city_list).filter(([cityId, cityName]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
                        // // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
                        if (province[provinceIndex].text == detail.province && cityItem[1] == detail.city) {
                            _areaCode = id
                            this.globalCode = _areaCode
                        }
                    }
                })
                return _areaCode;
            },
            async onSave(content) {
                const params = {
                    "city": content.city,
                    "defaultStatus": content.isDefault ? 1 : 0,
                    "detailAddress": content.addressDetail,
                    "name": content.name,
                    "phoneNumber": content.tel,
                    "postCode": content.areaCode,
                    "province": content.province,
                    "region": content.county
                }
                if (this.type == 'edit') {
                    params['addressId'] = this.addressId
                }
                await this.type == 'add' ? addAddress(params) : EditAddress(this.addressId, params)
                Toast('保存成功')
                setTimeout(() => {
                    this.$router.push({path: `address?from=${this.from}`})
                }, 1000)

            },
            async onDelete() {
                const {data} = await DeleteAddress(this.addressId)
                Toast('删除成功')
                setTimeout(() => {
                    this.$router.push({path: 'address'})
                }, 1000)
            },
            goBack() {
                this.$router.go(-1)
            },
        }
    }
</script>

<style lang="less">
    @import '../../../common/style/mixin';

    .address-edit-box {
        margin-top: 44px;

        .van-address-edit {
            .van-button--danger {
                background: @primary;
                border-color: @primary;
            }

            .van-switch--on {
                background: @primary;
            }
        }
    }
</style>